﻿using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace EC.Merchant.Controllers
{
    using EC.Application.Interface;
    using EC.Entity;
    using EC.Entity.Enum;
    using EC.Entity.Request.Login;
    using EC.Merchant.Request;
    using EC.Util;
    using Google_Authenticator_netcore;
    using Microsoft.AspNetCore.Http;

    /// <summary>
    /// 登录控制器
    /// </summary>
    public class AccountController : Controller
    {
        #region 注入
        /// <summary>
        /// 用户
        /// </summary>
        private readonly LoginService _loginService;

        private IHttpContextAccessor _accessor;


        private readonly IPTableService _ipTableService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataBase">菜单</param>
        public AccountController(LoginService loginService, IHttpContextAccessor accessor, IPTableService ipTableService)
        {
            _loginService = loginService;
            _accessor = accessor;
            _ipTableService = ipTableService;
        }

        #endregion

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Login()
        {

            // 获取请求模型
            ViewBag.Ip = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Test()
        {

            // 获取请求模型
            ViewBag.Ip = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GoogleVerify()
        {
            var account = MemoryCacheUtil.Get<string>("GoogleVerify");
            //获取用户
            var user = _loginService.GetByAccount(account);
            if (user == null)
            {
                return Json(new JResult()
                {
                    Success = false,
                    Message = "用户不存在."
                });
            }
            var setupCode = new TwoFactorAuthenticator().GenerateSetupCode("911pay", user.Account, user.SecretKey, 300, 300);
            ViewBag.qrCodeImageUrl = setupCode.QrCodeSetupImageUrl;

            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> LoginVerify(LoginReqeust reqeust)
        {
            try
            {
                //账号
                if (string.IsNullOrEmpty(reqeust.Account))
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        Message = "用户名不能为空."
                    });
                }

                var accountReg = new Regex(@"^[A-Za-z0-9]+$");
                if (!accountReg.IsMatch(reqeust.Account))
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        Message = "用户名由数字、字母组成."
                    });
                }

                if (string.IsNullOrEmpty(reqeust.Password))
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        Message = "密码不能为空."
                    });
                }

                //获取用户
                var response = _loginService.Login(new LoginRequest()
                {
                    Account = reqeust.Account,
                    Password = reqeust.Password
                });

                if (response.Success && response.Data != null)
                {
                    var data = response.Data;

                    if (data.GoogleVerifyStatus == (int)GoogleVerifyStatus.启用)
                    {
                        var setupCode = new TwoFactorAuthenticator().GenerateSetupCode("911pay", data.UserName, data.SecretKey, 200, 200);

                        MemoryCacheUtil.Set("GoogleVerify", data.UserName, 10);

                        return Json(new JResult()
                        {
                            Success = true,
                            StatusCode = "Google"
                        });
                    }
                    else
                    {
                        var json = data.UserPermissions!=null? string.Join(", ", data.UserPermissions):"";

                        var claims = new List<Claim>() {
                            new Claim(ClaimTypes.Sid,data.UserId.ToString()),
                            new Claim(ClaimTypes.DenyOnlySid,data.MerchantId.ToString()),
                            new Claim(ClaimTypes.Role,EncryptionUtil.EnCryptDES(json))
                        };

                        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

                        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);

                        return Json(new JResult()
                        {
                            Success = true
                        });
                    }
                }
                else
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        Message = response.Message
                    });
                }

            }
            catch (Exception ex)
            {
                return Json(new JResult()
                {
                    Success = true,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Login(LoginReqeust reqeust)
        {
            try
            {
                //账号
                if (string.IsNullOrEmpty(reqeust.Account))
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        Message = "用户名不能为空."
                    });
                }

                var accountReg = new Regex(@"^[A-Za-z0-9]+$");
                if (!accountReg.IsMatch(reqeust.Account))
                {
                    return Json(new JResult() { 
                        Success = false,
                        Message = "用户名由数字、字母组成."
                    });
                }


                if (string.IsNullOrEmpty(reqeust.Password))
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        Message = "密码不能为空."
                    });
                }



                //获取用户
                var response = _loginService.Login(new LoginRequest()
                {
                    Account = reqeust.Account,
                    Password = reqeust.Password
                });

                if (response.Success && response.Data != null)
                {
                    var data = response.Data;

                    //google验证
                    TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                    if (!tfa.ValidateTwoFactorPIN(data.SecretKey, reqeust.VerifyCode, TimeSpan.FromSeconds(20)))
                    {
                        return Json(new JResult()
                        {
                            Success = false,
                            Message = "Google验证失败."
                        });
                    }

                    var json = data.UserPermissions != null ? string.Join(", ", data.UserPermissions) : "";

                    var claims = new List<Claim>() {
                            new Claim(ClaimTypes.Sid,data.UserId.ToString()),
                            new Claim(ClaimTypes.DenyOnlySid,data.MerchantId.ToString()),
                            new Claim(ClaimTypes.Role,EncryptionUtil.EnCryptDES(json))
                        };

                    var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                    ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);

                    return Json(new JResult()
                    {
                        Success = true
                    });
                }
                else
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        Message = response.Message
                    });
                }
            }
            catch(Exception ex)
            {
                return Json(new JResult()
                {
                    Success = true,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// 注销
        /// </summary>
        [HttpGet]
        public IActionResult Logout()
        {
            Task.Run(async () =>
            {
                await HttpContext.SignOutAsync();
            }).Wait();

            return View("Login");
        }

        /// <summary>
        /// 预留重置方法
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult ResetCache()
        {
            _ipTableService.ResetCache((int)SystemType.商户管理);
            return Json(new { Message = "重置成功" });
        }
    }
}
